package com.backend.service.rbac.impl;

import cn.hutool.core.bean.BeanUtil;
import com.backend.mapper.rbac.RoleMapper;
import com.backend.service.rbac.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.constant.MessageConstant;
import com.common.exception.RoleException;
import com.pojo.dto.RoleDTO;
import com.pojo.dto.UpdateRoleNameDTO;
import com.pojo.entity.Role;
import com.pojo.vo.RoleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    RoleMapper roleMapper;
    @Override
    public Boolean addRole(RoleDTO roleDTO) {
        Role role = BeanUtil.copyProperties(roleDTO, Role.class);
        role.setCreateDatetime(LocalDateTime.now());
        role.setUpdateDatetime(LocalDateTime.now());
        role.setStatus(0);
        boolean save = save(role);
        return save;
    }

    @Override
    public Integer removeRoleByUsername(String username) {
        Integer result = roleMapper.removeRoleByUsername(username);
        return result;
    }

    @Override
    public List<Role> getAllRoles() {
        List<Role> roles = roleMapper.getAllRoles();
        return roles;
    }

    @Override
    public Integer updateRoleName(UpdateRoleNameDTO updateRoleNameDTO) {
        String name = updateRoleNameDTO.getRole();
        Role role = roleMapper.getRoleByName(name);
        if (role == null) {
            throw new RoleException(MessageConstant.ROLE_NOT_EXISTS);
        }
        Integer result = roleMapper.updateRoleName(updateRoleNameDTO);
        return result;
    }

    @Override
    public RoleVO getRoleByName(String name) {
        Role role = roleMapper.getRoleByName(name);
        if (role == null) {
            throw new RoleException(MessageConstant.ROLE_NOT_EXISTS);
        }
        RoleVO roleVO = BeanUtil.copyProperties(role, RoleVO.class);
        return roleVO;
    }

    @Override
    public Integer updateRoleStatus(String name, Integer status) {
        Integer result = roleMapper.updateRoleStatus(name, status);
        return result;
    }
}
